package com.mls.fivedistrict.util.http;

import com.baidu.aip.ocr.AipOcr;
import com.google.gson.Gson;
import com.mls.fivedistrict.entity.response.BDOCRIDResponse;
import com.mls.fivedistrict.util.Base64Img;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;

/**
 * Created by chenxiuxiang on 2018/6/14.
 */
@Slf4j
public class BDOcrClient {
    //设置APPID/AK/SK
    public static final String APP_ID = "11399641";
    public static final String API_KEY = "mb5GO0m1gZHzVCabDDD1QU0U";
    public static final String SECRET_KEY = "c6MkaLH0H8eiwMgNNbLkXRZsoLXTHO5x";


    private BDOcrClient() {
        lastDate = new Date();
        aipOcr = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
        log.info("获取AipOcr");

    }

    private static AipOcr aipOcr;
    private static Date lastDate;

    /**
     * access_token 有效期为30天
     *
     * @return
     */
    public static AipOcr getInstance() {
        if (aipOcr == null || lastDate == null || ((lastDate.getTime() + 29 * 24 * 60 * 60 * 1000) < new Date().getTime())) {
            new BDOcrClient();
        }
        return aipOcr;

    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        AipOcr client = getInstance();
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("detect_direction", "true");
        options.put("detect_risk", "true");

        String idCardSide = "front";

        // 参数为本地图片路径

        String image = "https://dwqvip.oss-cn-shenzhen.aliyuncs.com/image/d777efa2-7d1e-405f-b83e-323e118111ed.jpg?x-oss-process=image/resize,m_mfit,h_800,w_800";
        byte[] imageFromNetByUrl = Base64Img.getImageFromNetByUrl(image);
        JSONObject res = client.idcard(imageFromNetByUrl, "front", options);
        String s = new Gson().toJson(res);
        log.info("S:{}", s);
        BDOCRIDResponse bdocridResponse = new Gson().fromJson(s, BDOCRIDResponse.class);
        String imageback = "https://dwqvip.oss-cn-shenzhen.aliyuncs.com/image/5a1e9120-d9a7-4ec7-9662-d98eca4ec03d.jpg?x-oss-process=image/resize,m_mfit,h_800,w_800";
        byte[] imageFromNetByUrlback = Base64Img.getImageFromNetByUrl(imageback);
        JSONObject resback = client.idcard(imageFromNetByUrlback, idCardSide, options);
        String back = new Gson().toJson(resback);
        log.info("back{}", back);

    }


}
